<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

        <!DOCTYPE html>
        <html>

        <head>
            <meta charset="UTF-8">
            </meta>
            <base href="${pageContext.request.contextPath}/">
            <title>购物车_${site}</title>
            <link rel="stylesheet" type="text/css" href="/css/index.css" />
            <script src="/js/jquery-3.6.0.js"></script>
            <script src="/layer/layer.js"></script>
            <script>

                // 购物车总价
                var alltotal = 0;
                $(
                    $.ajax({
                        type: "GET",
                        url: "cart?opr=getList",
                        dataType: "JSON",
                        beforeSend: function (r) {
                            //加载层-默认风格
                            layer.load();
                        },
                        success: function (msg, status, xhr) {
                            // let alltotal = 0;
                            $.each(msg, function (infoIndex, info) {
                                let name = info["goods"][0]["bookName"];
                                let img = info["goods"][0]["img"];
                                let price = (info["goods"][0]["sellingPrice"]).toFixed(2);
                                let id = info["id"];
                                let gid = info["goods"][0]["id"];
                                // let price = info["price"].toFixed(2);
                                let nums = info["num"];
                                let total = (price * nums).toFixed(2);
                                alltotal = parseFloat(total) + parseFloat(alltotal);

                                $("#goodsList").prepend("<tr id='tr_" + gid + "'" + ">"
                                    + "<td class='ftd'><input type='checkbox' onclick='cMore()' name='checkbox' class='checkbox' data-gid='" + gid + "' id='checkbox_" + id + "'" + "value=" + id + "></td>"
                                    + "<td >"
                                    + "<img src=" + img + " alt=" + name + " title=" + name + ">" + "</td><td name='gname'>"
                                    + name + "</td><td name='gprice' class='gprice' id='gprice_" + id + "'" + ">"
                                    + price + "</td><td> <div class='num'>"
                                    + "<a class='reduce'  href='javascript:void(0)' data-gid='" + gid + "' title=" + id + ">-</a><input type='text' name='gnums' class='tiny' id='nums_" + gid + "' value=" + nums + ">"
                                    + "<a class='add'  href='javascript:void(0)' data-gid='" + gid + "' title=" + id + ">+</a></div></td><td class='totals'>￥<b class='red2' id='price_" + id + "'" + ">"
                                    + total + "</b></td><td>"
                                    + "<a href='javascript:void(0)'> <img src='images/admin/sc.png' alt='删除' id='delID' title='删除' data-gid='" + gid + "'  style='height: 13px; width: 13px;' class='del'/>"
                                    + "</a></td></tr>")
                            })
                            $("#sum_price").text(0);
                        },
                        complete: function (XMLHttpRequest, textStatus) {
                            // alert('远程调用成功，状态文本值：'+textStatus);
                            layer.closeAll('loading');
                        },
                        error: function (msg) {
                            layer.msg('系统繁忙，请稍后再试', { icon: 2 });
                        }
                    })

                )

                // function cAll() {
                //     $(":checkbox").prop("checked", $(this).prop("checked"));
                //     // 计算总价
                //     getAllToltalprice()
                // }
                function cMore() {
                    // 计算价格
                    getAllToltalprice();
                    // 判断是否选中
                    ischecked();
                }

                $(function () {
                    // 全选按钮
                    $("#checkAll").click(function () {
                        $(":checkbox").prop("checked", $(this).prop("checked"));
                        // 计算总价
                        getAllToltalprice()

                    })

                    // // 单个checkbox
                    // $(".checkbox").click(function () {
                    //     // 计算价格
                    //     getAllToltalprice();
                    //     // 判断是否选中
                    //     ischecked();

                    // })

                })
                // 判断是否选中
                function ischecked() {
                    if ($(".checkbox:checked").length == $(".checkbox").length) {
                        $("#checkAll").prop("indeterminate", false)
                        $("#checkAll").prop("checked", true)
                    } else if ($(".checkbox:checked").length == 0) {
                        $("#checkAll").prop("checked", false)
                    } else {
                        $("#checkAll").prop("indeterminate", true)
                    }
                }

                function changNums(num, gid) {
                    $.ajax({
                        type: "get",
                        url: "cart",
                        data: "opr=changeNum&num=" + num + "&gid=" + gid,
                        dataType: "json",
                        beforeSend: function (r) {
                            //加载层-默认风格
                            layer.load();
                        },
                        success: function (result) {
                            if (result.msg == 'ok') {
                                layer.msg('ok', {
                                    time: 1000 //1s后自动关闭
                                });
                            } else {
                                layer.msg('系统繁忙，请稍后再试', { icon: 2 });
                            }
                        },
                        complete: function (XMLHttpRequest, textStatus) {
                            // alert('远程调用成功，状态文本值：'+textStatus);
                            layer.closeAll('loading');
                        },
                        error: function () {
                            layer.msg('系统繁忙，请稍后再试', { icon: 2 });
                        }
                    })
                }


                $(function () {
                    // -
                    $(".reduce").on("click", function () {
                        let changegid = this.getAttribute("data-gid");
                        let num = $(this).next(".tiny").val()
                        // 单个商品选中
                        $("#checkbox_" + this.title).prop("checked", true);
                        if (num > 1) {
                            num = num - 1;
                            // 单个商品价格
                            $("#price_" + this.title).text(($("#gprice_" + this.title).text() * num).toFixed(2))
                            // 计算总价
                            getAllToltalprice()
                            // 修改数据库数量
                            changNums(num, changegid)

                        }
                        // 判断是否选中
                        ischecked();
                        $(this).next(".tiny").val(num);
                    })
                    // +
                    $(".add").on("click", function () {
                        let changegid = this.getAttribute("data-gid");
                        let num = parseInt($(this).prev(".tiny").val())
                        // 单个商品选中
                        $("#checkbox_" + this.title).prop("checked", true);
                        if (num < 100) {
                            num = num + 1;
                            // 单个商品价格
                            $("#price_" + this.title).text(($("#gprice_" + this.title).text() * num).toFixed(2));
                            // 计算总价
                            getAllToltalprice();
                            // 修改数据库数量
                            changNums(num, changegid)
                        }
                        // 判断是否选中
                        ischecked();
                        $(this).prev(".tiny").val(num)
                    })
                    // 输入框控制
                    var regNum = 0;
                    $(".tiny").on("mousedown", function () {
                        regNum = $(this).val();
                    })
                    $(".tiny").on("blur", function () {
                        if (isNaN($(this).val())) {
                            $(this).val(regNum);
                        }
                    })
                })
                // 删除
                $(function () {

                    $(".del").on("click", function () {
                        let gid = this.getAttribute("data-gid");
                        layer.confirm('您确定删除吗？', {
                            btn: ['确定', '取消'] //按钮
                        }, function () {
                            $.ajax({
                                type: "get",
                                url: "cart",
                                data: "opr=del&gid=" + gid,
                                dataType: "json",
                                success: function (result) {
                                    if (result.msg == 'ok') {
                                        // 移除tr
                                        $("tr").remove("#tr_" + gid);
                                        layer.msg('删除成功', { icon: 1 });
                                    } else {
                                        layer.msg('系统繁忙，请稍后再试', { icon: 2 });
                                    }
                                },
                                complete: function () {
                                    //加载层-风格3
                                    layer.load(2);
                                    //此处演示关闭
                                    setTimeout(function () {
                                        layer.closeAll('loading');
                                    }, 2000);
                                },
                                error: function () {
                                    layer.msg('系统繁忙，请稍后再试', { icon: 2 });
                                }
                            })
                        }, function () {
                            layer.closeAll('dialog');
                        });
                    })
                })

                // 计算总价
                function getAllToltalprice() {
                    let p = 0;
                    // 获取所有选中的选中框
                    let allchecked = $(".checkbox:checked");
                    // 循环选中的
                    for (const c of allchecked) {
                        // 累加价格
                        let prices = $(c).parent(".ftd").next().next().next().next().next().find(".red2").html();
                        p += parseFloat(prices);
                    }
                    // DOM改变
                    $("#sum_price").text(p);
                }
                // 清空所选
                $(function () {
                    $("#delAll").click(function () {
                        let gids = '';
                        // 获取所有选中的选中框
                        let allchecked = $(".checkbox:checked");
                        // 循环选中的拼接参数
                        for (const c of allchecked) {
                            gids += '&gids=' + c.getAttribute("data-gid");
                        }
                        // DOM改变

                        // ajax
                        $.ajax({
                            type: "post",
                            url: "cart",
                            data: "opr=delAll" + gids,
                            dataType: "json",
                            success: function (result) {
                                if (result.msg == 'ok') {
                                    // 循环选中的
                                    for (const c of allchecked) {
                                        let gid = c.getAttribute("data-gid");
                                        // 移除tr
                                        $("tr").remove("#tr_" + gid);
                                        layer.msg('删除成功', { icon: 1 });
                                    }
                                } else {
                                    layer.msg('系统繁忙，请稍后再试', { icon: 2 });
                                }

                            },
                            error: function () {
                                layer.msg('系统繁忙，请稍后再试', { icon: 2 });
                            }
                        })
                    })
                })
            </script>
            <script>
                function finish() {
                    let gids = '';
                    let nums = '';
                    // 获取所有选中的选中框
                    let allchecked = $(".checkbox:checked");
                    // 循环选中的拼接参数
                    for (const c of allchecked) {
                        gids += '&goodsid=' + c.getAttribute("data-gid");
                        nums += '&num=' + $("#nums_" + c.getAttribute("data-gid")).val();
                    }
                    if (gids == '' || nums == '') {
                        layer.msg('您还未选择商品', function () {
                            //关闭后的操作
                        });
                    } else {
                        location.href = "/order?opr=add" + gids + nums;
                    }
                }

            </script>
        </head>

        <body class="second">
            <div class="brand_list container_2">
                <jsp:include page="header.jsp"></jsp:include>
                <div class="wrapper clearfix">
                    <div class="position mt_10">
                        <span>您当前的位置：</span> <a href=""> 首页</a> » 购物车
                    </div>
                    <div class="myshopping m_10">
                        <ul class="order_step">
                            <li class="current"><span class="first">1、查看购物车</span></li>
                            <li><span>2、填写核对订单信息</span></li>
                            <li class="last"><span>3、成功提交订单</span></li>
                        </ul>

                    </div>
                    <form action="order_add" id="form1">
                        <table width="100%" class="cart_table m_10">
                            <col width="80px" />
                            <col width="115px" />
                            <col width="400px" />
                            <col width="80px" />
                            <col width="80px" />
                            <col width="80px" />
                            <caption>查看购物车</caption>
                            <thead>
                                <tr>
                                    <th> <input type="checkbox" name="checkAll" id="checkAll"> <label
                                            for="checkAll">全选</label> </th>
                                    <th>图片</th>
                                    <th>商品名称</th>
                                    <th>单价</th>
                                    <th>数量</th>
                                    <th>小计</th>
                                    <th class="last">操作</th>
                                </tr>
                            </thead>
                            <tbody id="goodsList">

                                <tr class="stats">
                                    <td><a href="javascript:void(0)" id="delAll">清空所选</a></td>
                                    <td colspan="8">金额总计（不含运费）：<b class="orange" id='sum_price'>0</b>￥&nbsp;</td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="2" class="t_l"></td>
                                    <td colspan="6" class="t_r"><a class="btn_continue" href="javascript:void(0)"
                                            onClick="javascript:history.back()">继续购物</a>
                                        <a class="btn_pay" href="javascript:finish();">去结算</a>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </form>
                    <!-- <div class="box">
                        <div class="title">热门商品推荐</div>
                    </div> -->
                    <ul id="scrollpic" class="prolist">

                    </ul>
                </div>
                <jsp:include page="footer.jsp" />
            </div>
        </body>

        </html>